package npu.dce.andcontact1;

import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.graphics.BitmapFactory;
import android.widget.ImageView; 
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;

public class SyncSchedule extends Activity {

		private MediaPlayer mMediaPlayer; 

		// UI controls	
		private Button btnSave;
		private EditText editGivenName, editMiddleName, editFamilyName, editPhone, editEmail, 
		         editIM, editStreet, editPOBox, editCity, editState, editZipCode, editCountry, 
		         editSNS, editOrg1, editOrg2, editNotes;
		private RadioButton btnMan, btnWoman;
		private Spinner spinPhone, spinEmail, spinIM, spinPostalAddr, spinSNS, spinOrg1, spinOrg2;
		
		private ContactDBAdapter mDbHelper;
		private long contact_id, id = 0;	
		
		private static final String contactID = "id";
		
		private static final int CAMERA_REQUEST = 1888;  
	    private ImageView imageView; 
	       
	    private SQLiteDatabase db;
		private Handler mHandler = new Handler(); 
		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);

			setContentView(R.layout.schedule);
			
			this.mDbHelper = new ContactDBAdapter(this);                  
	        this.imageView = (ImageView)this.findViewById(R.id.imageView1); 
        
	        Intent intent = getIntent();
	        this.id = intent.getLongExtra(contactID, 0);
	       
	        if(id != 0)
	        {
	        	this.getNamePhone(id);
	        	btnSave.setText("Update");
	        	
	        }	
	        	        
	        UpdatePacket update = new UpdatePacket();

	        //Running thread    
	        mHandler.postDelayed(new Runnable() {             
	        	public void run() {                 
	        		doStuff();             
	        	}         
	        }, 5000); 
	               
	        Thread t1 = new Thread(new Server(update, mDbHelper));
	        Thread t2 = new Thread(new Server1(mDbHelper));
	        Thread t3 = new Thread(new Server2(mDbHelper));
	        Thread t4 = new Thread(new Server3(mDbHelper));
	        Thread t5 = new Thread(new Server4(mDbHelper));	        
	        
	        t1.start();
	        t2.start();
	        t3.start();
	        t4.start();
			t5.start();
			
			Button buttonDismiss = (Button)findViewById(R.id.dismiss);
			
			buttonDismiss.setOnClickListener(new Button.OnClickListener(){
	
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					mMediaPlayer.stop();
					finish();
					
				}});
			
			playSound(this, getAlarmUri());
			
		} //onCreate

		private void doStuff() {        
	   	 
	    	Context context = getApplicationContext();
	        int duration = Toast.LENGTH_SHORT;
	    	
	    	Thread t = new Thread(new Group_Join_Client(mDbHelper));
	    	Toast toast1 = Toast.makeText(context,"Start client thread after 5 sec", duration);
	        toast1.show();        	
	        t.start();     	
	    } 
	    
	    private void getNamePhone(long id) {
	        this.mDbHelper.open(); 
	        
	        Cursor cursor = this.mDbHelper.fetchContact(id);
	        
			if(cursor != null)
				cursor.moveToFirst();
			
			byte[] blob = cursor.getBlob(cursor.getColumnIndex(this.mDbHelper.KEY_PHOTO));
			imageView = (ImageView)findViewById(R.id.imageView1);
			imageView.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length)); 
			
			editGivenName.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_GIVENNAME)));
			editMiddleName.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_MIDDLENAME)));
			editFamilyName.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_FAMILYNAME)));

			String gender = cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_GENDER));
			if(gender.equals(btnMan.getText().toString()))			
				btnMan.setChecked(true);
			else
				btnWoman.setChecked(true);

			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINPHONE)), spinPhone);
			editPhone.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_PHONE)));
			
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINEMAIL)), spinEmail);
			editEmail.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_EMAIL)));
			
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINIM)), spinIM);
			editIM.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_IM)));		       

			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINADDR)), spinPostalAddr);
			editStreet.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_STREET)));
			editPOBox.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_POBOX)));
			editCity.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_CITY)));
			editState.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_STATE)));
			editZipCode.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_ZIPCODE)));
			editCountry.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_COUNTRY)));
							
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINSNS)), spinSNS);
			editSNS.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SNS)));
			
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINORG1)), spinOrg1);
			editOrg1.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_ORG1)));
			
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINORG2)), spinOrg2);
			editOrg2.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_ORG2)));
			
			editNotes.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_NOTES)));

			cursor.close();

	        this.mDbHelper.close();	
	    }
	    
	    private void setSpinnerItem(String text, Spinner spinner) {
	    	ArrayAdapter adapter = (ArrayAdapter)spinner.getAdapter();
	    	int pos = adapter.getPosition(text);
	    	spinner.setSelection(pos);
	    }
	    
		private void playSound(Context context, Uri alert) {
			
			mMediaPlayer = new MediaPlayer();
		
			try {
				mMediaPlayer.setDataSource(context, alert);
				final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		
				if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
					mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
					mMediaPlayer.prepare();
					mMediaPlayer.start();
				}
				
			} catch (IOException e) {
				System.out.println("OOPS");
			}
		}
		//Get an alarm sound. Try for an alarm. If none set, try notification, 
		//Otherwise, ringtone.
		private Uri getAlarmUri() {
		
			Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
		
			if (alert == null) {
				
				alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
				
				if (alert == null) {
					alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
				}
			}
			return alert;
		}		
}